package com.clstu.button;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 带按钮的窗口
 */
public class ButtonFrame extends JFrame {
    private  JPanel buttonPanel;
    private static final int width = 300;
    private static final int height = 200;

    public static void main(String[] args) {
        new ButtonFrame();
    }

    public ButtonFrame(){
        setSize(width,height);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //create buttons
        JButton yellowButton = new JButton("Yellow");
        JButton blueButton = new JButton("Blue");
        JButton redButton = new JButton("Red");

        buttonPanel = new JPanel();

        //add button to panel
        buttonPanel.add(yellowButton);
        buttonPanel.add(blueButton);
        buttonPanel.add(redButton);

        //add panel to frame
        add(buttonPanel);

        //create button actions
        ColorAction yellowAction = new ColorAction(Color.yellow);
        ColorAction blueAction = new ColorAction(Color.blue);
        ColorAction redAction = new ColorAction(Color.RED);

    }

    private class ColorAction implements ActionListener{
        private final Color backgroundColor;

        public ColorAction(Color backgroundColor) {
            this.backgroundColor = backgroundColor;
        }

        @Override//监听 一旦有事件发生就产生事件类,调用这个方法,更换颜色
        public void actionPerformed(ActionEvent e) {
            buttonPanel.setBackground(backgroundColor);
            buttonPanel.repaint();
        }
    }


}

//class MyPanel extends JPanel{
//    public MyPanel(){
//
//    }
//
//    @Override
//    public void paint(Graphics g) {
//
//    }
//
//    @Override
//    public void setBackground(Color bg) {
//
//    }
//}
